package com.lemon.stock.compose.mine

import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lemon.java.storage.FileUtil
import com.lemon.java.system.Permission
import com.lemon.stock.R
import com.lemon.stock.compose.permissionDialog
import com.lemon.stock.util.PermissionsChecker
import com.lemon.stock.util.showMessage
import com.lemon.stock.viewmodel.ImportViewModel
import java.io.BufferedReader
import java.io.FileInputStream
import java.io.InputStreamReader


private var warningWords = ""

@Composable
fun ImportScreen(onback: () -> Unit){

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(text = stringResource(id = R.string.menu_import)) },
                elevation = 8.dp,
                navigationIcon = {
                    IconButton(onClick = onback) {
                        Icon(Icons.Filled.ArrowBack, contentDescription = null)
                    }
                }
            )
        }
    ){
        val mViewModel: ImportViewModel = viewModel()

        val importState = mViewModel.process.observeAsState()

        Column(
            verticalArrangement = Arrangement.Top,
            modifier = Modifier.fillMaxSize()
        ) {
            when(importState.value){
                ImportState.ready -> ImportReady(mViewModel)
                ImportState.again -> ImportReady(mViewModel)
                ImportState.importing -> DataInHandle()
                ImportState.success -> ImportSuccess(mViewModel)
                ImportState.fail -> ImportFail(mViewModel)
                ImportState.permission -> PermissionsDialog(mViewModel)
            }
        }
    }
}

@Composable
fun PermissionsDialog(mViewModel: ImportViewModel){
    permissionDialog(warningWords) {
        mViewModel.changeProcess(ImportState.again)
    }
}

@Composable
fun ImportSuccess(mViewModel: ImportViewModel){
    Column(
        verticalArrangement = Arrangement.Top,
        modifier = Modifier.fillMaxSize()
    ) {
        Spacer(modifier = Modifier.height(20.dp))
        Image(
            painter = painterResource(R.drawable.ic_img_success),
            modifier = Modifier
                .size(90.dp)
                .align(Alignment.CenterHorizontally),
            //contentScale = ContentScale.Crop,
            contentDescription = null
        )
        Spacer(modifier = Modifier.height(20.dp))

        Text("导入成功:" + mViewModel.message)
    }

}

@Composable
fun ImportFail(mViewModel: ImportViewModel){
    Column(
        verticalArrangement = Arrangement.Top,
        modifier = Modifier.fillMaxSize()
    ) {
        Image(
            painter = painterResource(R.drawable.ic_img_fail),
            modifier = Modifier
                .size(50.dp)
                .align(Alignment.CenterHorizontally),
            //contentScale = ContentScale.Crop,
            contentDescription = null
        )
        Spacer(modifier = Modifier.height(5.dp))

        Text("导入失败，原因可能是:" + mViewModel.message)
    }
}


@Composable
fun ImportReady(mViewModel: ImportViewModel){
    Text(text = "导入数据是为了初始化数据，请从你的证券机构中导出excel文件，并保存csv格式。")
    Text(text = "为了保证导入顺利，请确保excel文件(最终为CSV文件)的第一行为表头，并且表头须包含以下字段：")
    Text(text = "数据文件的导入有两种方式：")
    LocalUpload(mViewModel)
    Text(text = "2. 在电脑上，上传至服务器（须先注册为会员）")
}

@Composable
fun DataInHandle(){
    Image(
        painter = painterResource(id = R.mipmap.mo_upload),
        contentDescription = null,
        //modifier = Modifier.size(55.dp),
        //contentScale = ContentScale.Crop
    )
}

@Composable
fun LocalUpload(mViewModel: ImportViewModel){
    val context = LocalContext.current

    val launcher: ActivityResultLauncher<Intent> =
        rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
            val intent: Intent? = activityResult.data
            if(intent!=null){
                val uri = intent.data
                mViewModel.importFromLocal(context, uri!!)
                //handleData(context = context, uri = uri!!)

            }
        }

    Text(text = "1. 从手机内存中选择")

    Button(onClick = {
        var mPermissioChecker = PermissionsChecker(context)
        var permissionListTmp = arrayOf<String>(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if(mPermissioChecker.lacksPermissions(*permissionListTmp)){
            warningWords = "读取手机存储权限"
            //if(mViewModel.process.value==ImportState.ready){
                mViewModel.changeProcess(ImportState.permission)
            //}
        }else{
            val intent = Intent(Intent.ACTION_GET_CONTENT).apply{
                addCategory(Intent.CATEGORY_DEFAULT)
                type = "*/*"
                //putExtra(Intent.EXTRA_TITLE, "export.db")
            }
            launcher.launch(intent)
        }

    }) {
        Text(text = "选择文件")
    }

    Spacer(modifier = Modifier.height(20.dp))

}
object ImportState{
    const val ready = 0
    const val importing = 1
    const val fail = 4
    const val again = 6
    const val permission = 7
    const val success = 8
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {

}